// Copyright Epic Games, Inc. All Rights Reserved.

#include "top_cmd.h"

#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/uid.h>
#include <zenutil/zenserverprocess.h>

#include <memory>

//////////////////////////////////////////////////////////////////////////

namespace zen {

TopCommand::TopCommand()
{
}

TopCommand::~TopCommand() = default;

int
TopCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
	ZEN_UNUSED(GlobalOptions, argc, argv);

	ZenServerState State;
	if (!State.InitializeReadOnly())
	{
		ZEN_CONSOLE("no Zen state found");

		return 0;
	}

	int		  n			   = 0;
	const int HeaderPeriod = 20;

	for (;;)
	{
		if ((n++ % HeaderPeriod) == 0)
		{
			ZEN_CONSOLE("{:>5} {:>6} {:>24}", "port", "pid", "session");
		}

		State.Snapshot([&](const ZenServerState::ZenServerEntry& Entry) {
			StringBuilder<25> SessionStringBuilder;
			Entry.GetSessionId().ToString(SessionStringBuilder);
			ZEN_CONSOLE("{:>5} {:>6} {:>24}", Entry.EffectiveListenPort.load(), Entry.Pid.load(), SessionStringBuilder);
		});

		zen::Sleep(1000);

		if (!State.IsReadOnly())
		{
			State.Sweep();
		}
	}

	return 0;
}

//////////////////////////////////////////////////////////////////////////

PsCommand::PsCommand()
{
}

PsCommand::~PsCommand() = default;

int
PsCommand::Run(const ZenCliOptions& GlobalOptions, int argc, char** argv)
{
	ZEN_UNUSED(GlobalOptions, argc, argv);

	ZenServerState State;
	if (!State.InitializeReadOnly())
	{
		ZEN_CONSOLE("no Zen state found");

		return 0;
	}

	State.Snapshot([&](const ZenServerState::ZenServerEntry& Entry) {
		ZEN_CONSOLE("Port {} : pid {}", Entry.EffectiveListenPort.load(), Entry.Pid.load());
	});

	return 0;
}

}  // namespace zen
